import serial
import serial.tools.list_ports

class Robot:
    def __init__(self, serial:serial.Serial):
        self.serial = serial
    
    def set_speed(self, idx, speed):
        if self.serial.is_open:
            self.serial.write(f":{idx} {speed}\n".encode())
            print(f":{idx} {speed}\n".encode())

        else:
            print("Serial port is not open")
            # print(f"Setting speed {speed} for motor {idx}")
    def set_position(self, idx):
        if self.serial.is_open:
            self.serial.write(f":{idx}\n".encode())
            print(f":{idx}\n".encode())

        else:
            print("Serial port is not open")
            # print(f"Setting speed {speed} for motor {idx}")
    
    
    

    def connect(self, port):
        self.serial.port = port
        self.serial.baudrate = 115200
        self.serial.open() 
        print(f"Serial port is {port}")
    
    def emergency_stop(self):
        ...
    
    def disconnect(self):
        
        if self.serial.is_open:
            self.serial.close()
            print(f"Serial port is closed")


class PortManager:
    def __init__(self):
        self.ports = []
        self.names = []
        ...
    def remove_port(self, port_name):
        if port_name in self.ports:
            self.ports.remove(port_name)
            # 更新UI或其他相关操作

    def get_ports(self):
        options = serial.tools.list_ports.comports()
        ports = [i.device for i in options]
        names = [i.description for i in options]
        self.ports = ports
        self.names = names
        return ports, names
    
    def name_to_port(self, name):
        idx = self.names.index(name)
        return self.ports[idx]

    def select_port(self, port_name):
        # 选择一个端口，并更新selected_port属性
        self.selected_port = port_name

    def get_selected_port(self):
        # 返回当前选择的端口
        return self.selected_port


    
